package com.x.utils;

import java.nio.charset.StandardCharsets;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.util.encoders.Base64;

@Slf4j
public class AESUtils {

  public static String decryptAES(String data, String key, String iv) throws Exception {
    try {
      byte[] encrypted1 = AESUtils.decode(data);
      Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
      SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
      IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));

      cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);

      byte[] original = cipher.doFinal(encrypted1);
      String originalString = new String(original, StandardCharsets.UTF_8);
      return originalString.trim();
    } catch (Exception e) {
      log.error("AESUtils.decryptAES error", e);
      return null;
    }
  }

  public static byte[] decode(String base64EncodedString) {
    return Base64.decode(base64EncodedString);
  }


}
